<?php

class TaskModel extends Model {
	public static $task_cache;
	
	public static function buildCache() {
		$folder = TASK;
		
		$tasks = array();
		
		// Read each dir
		$dir = dir($folder);
		while (false !== ($entry = $dir->read())) {
			if ($entry[0] == '.') continue;
			$folder = TASK . '/' . $entry;
			if (is_dir($folder)) {
				$task_file = $folder . '/task.cfg';
				if (file_exists($task_file)) {
					$task['path'] = $folder;
					$task['conf'] = parse_ini_file($task_file);
					
					$tasks[strtolower($entry)] = $task;
				}
			}
		}
		
		ksort($tasks);
		
		self::$task_cache = $tasks;
//		print_r($tasks);
	}
	
	public function taskExist($slug) {
		return isset(self::$task_cache[$slug]);
	}
	
	public function getTask($slug) {
		if (isset(self::$task_cache[$slug])) return self::$task_cache[$slug];
		return false;
	}
	
	public function getPDF($slug) {
		$arr = self::$task_cache;
		if (isset($arr[$slug])) {
			return $arr[$slug]['path'] . '/' . $arr[$slug]['conf']['pdf'];
		}
		return false;
	}
	
	public function getDoc($slug) {
		$arr = self::$task_cache;
		if (isset($arr[$slug])) {
			return $arr[$slug]['path'] . '/' . $arr[$slug]['conf']['doc'];
		}
		return false;
	}
	
	public function getAllTasks() {
		return self::$task_cache;
	}
	
	public function getTaskHTML($slug) {
		$arr = self::$task_cache;
		if (isset($arr[$slug])) {
			$file = $arr[$slug]['path'] . '/' . $arr[$slug]['conf']['html'];
			if (file_exists($file)) {
				return iconv('windows-874','UTF-8',file_get_contents($file));
			}
			return false;
		}
		return false;
	}
}

TaskModel::buildCache();
